package com.kgc.itrip.service.impl;

import com.kgc.itrip.common.*;
import com.kgc.itrip.component.SystemConfig;
import com.kgc.itrip.mapper.ItripHotelOrderMapper;
import com.kgc.itrip.mapper.ItripHotelRoomMapper;
import com.kgc.itrip.mapper.ItripHotelTempStoreMapper;
import com.kgc.itrip.mapper.ItripOrderLinkUserMapper;
import com.kgc.itrip.pojo.*;
import com.kgc.itrip.service.ItripHotelOrderService;
import com.kgc.itrip.vo.order.ItripAddHotelOrderVO;
import com.kgc.itrip.vo.order.ItripListHotelOrderVO;
import com.kgc.itrip.vo.order.ItripModifyHotelOrderVO;
import com.kgc.itrip.vo.order.ItripPersonalOrderRoomVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItripHotelOrderServiceImpl implements ItripHotelOrderService {

    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ItripHotelRoomMapper itripHotelRoomMapper;
    @Resource
    private ItripOrderLinkUserMapper itripOrderLinkUserMapper;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;
    public ItripHotelOrder getItripHotelOrderById(Long id)throws Exception{
        return itripHotelOrderMapper.getItripHotelOrderById(id);
    }

    public List<ItripHotelOrder> getItripHotelOrderListByMap(Map<String,Object> param)throws Exception{
        return itripHotelOrderMapper.getItripHotelOrderListByMap(param);
    }

    public Integer getItripHotelOrderCountByMap(Map<String,Object> param)throws Exception{
        return itripHotelOrderMapper.getItripHotelOrderCountByMap(param);
    }

    public Integer itriptxAddItripHotelOrder(ItripHotelOrder itripHotelOrder)throws Exception{
        itripHotelOrder.setCreationDate(new Date());
        return itripHotelOrderMapper.insertItripHotelOrder(itripHotelOrder);
    }

    public Integer itriptxModifyItripHotelOrder(ItripHotelOrder itripHotelOrder)throws Exception{
        itripHotelOrder.setModifyDate(new Date());
        return itripHotelOrderMapper.updateItripHotelOrder(itripHotelOrder);
    }

    public Integer itriptxDeleteItripHotelOrderById(Long id)throws Exception{
        return itripHotelOrderMapper.deleteItripHotelOrderById(id);
    }

    public Page<ItripListHotelOrderVO> queryItripHotelOrderPageByMap(Map<String,Object> param, Integer pageNo, Integer pageSize)throws Exception{
        Integer total = itripHotelOrderMapper.getItripHotelOrderCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<ItripListHotelOrderVO> itripHotelOrderList = itripHotelOrderMapper.getItripHotelOrderListByMapTwo(param);
        page.setRows(itripHotelOrderList);
        return page;
    }

    @Override
    public Integer getHotelRoomStoreByCondition(Map<String, Object> params) throws Exception {
        //1.根据条件调用存储过程刷新库存
        itripHotelOrderMapper.flushTempStore(params);
        //2.根据条件查询最小库存
        List<ItripHotelTempStore> itripHotelList = itripHotelOrderMapper.getItripHotelListByCondition(params);
        return itripHotelList.get(0).getStore();
    }

    @Override
    public boolean getValidateRoomStore(Map<String, Object> params) throws Exception {
        //1.根据条件调用存储过程刷新库存
        itripHotelOrderMapper.flushTempStore(params);
        //2.根据条件查询最小库存
        List<ItripHotelTempStore> itripHotelList = itripHotelOrderMapper.getItripHotelListByCondition(params);
        //3.获取最小库存
        Integer minStore = this.getHotelRoomStoreByCondition(params);
        Integer count = (Integer) params.get("count");
        return count <= minStore;
    }

    @Override
    public Map<String, Object> itriptxCreateItripHotelOrder(ItripAddHotelOrderVO itripAddHotelOrderVO
            , ItripUser user,String token) throws Exception {
        //1.封装数据
        ItripHotelOrder hotelOrder = new ItripHotelOrder();
        BeanUtils.copyProperties(itripAddHotelOrderVO,hotelOrder);
        hotelOrder.setUserId(user.getId());
        //生成订单号：机器码+日期（MD5)(商品IDs+毫秒数+1000000的随机数）
        //（MD5)(商品IDs+毫秒数+1000000的随机数）
        StringBuffer md5Str = new StringBuffer();
        md5Str.append(itripAddHotelOrderVO.getHotelId());
        md5Str.append(itripAddHotelOrderVO.getRoomId());
        md5Str.append(System.currentTimeMillis());
        md5Str.append(Math.random()*1000000);
        String md5 = MD5.getMd5(md5Str.toString(),6);
        //生成订单号
        String orderNo = systemConfig.getMachineCode()
                +DateUtil.format(new Date(),"yyyyMMddhhmmss")+md5;
        hotelOrder.setOrderNo(orderNo);
        //计算预定的天数
        List<Date> betweenDates = DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(), itripAddHotelOrderVO.getCheckOutDate());
        Integer bookingDays = betweenDates.size()-1;
        hotelOrder.setBookingDays(bookingDays);
        //设置订单状态
        hotelOrder.setOrderStatus(Constants.ORDER_STATUS.TO_PAY);
        //计算支付的金额=单价*天数*房间数
        ItripHotelRoom itripHotelRoom = itripHotelRoomMapper.getItripHotelRoomById(itripAddHotelOrderVO.getRoomId());
        BigDecimal totalAmount = BigDecimalUtil.OperationASMD(itripHotelRoom.getRoomPrice(), bookingDays * itripAddHotelOrderVO.getCount(),
                BigDecimalUtil.BigDecimalOprations.multiply, 2, BigDecimal.ROUND_DOWN);
        hotelOrder.setPayAmount(totalAmount.doubleValue());
        //设置入住人姓名
        List<ItripUserLinkUser> linkUser = itripAddHotelOrderVO.getLinkUser();
        String linkUserName = "";
        for (int i = 0; i < linkUser.size(); i++) {
            linkUserName += linkUser.get(i).getLinkUserName();
            if (i != linkUser.size() - 1) {
                linkUserName += ",";
            }
        }
        hotelOrder.setLinkUserName(linkUserName);
        //设置预定端
        if (token.startsWith("token:PC-")){
            hotelOrder.setBookType(Constants.BOOKTYPE.PC);
        }else if (token.startsWith("token-WEB-")){
            hotelOrder.setBookType(Constants.BOOKTYPE.MOBILE);
        }else{
            hotelOrder.setBookType(Constants.BOOKTYPE.OTHER);
        }
        //2.添加订单
        if (itripAddHotelOrderVO.getId()==null){//添加订单
            //设置创建时间
            hotelOrder.setCreationDate(new Date());
            //设置创建人
            hotelOrder.setCreatedBy(user.getId());
            itripHotelOrderMapper.insertItripHotelOrder(hotelOrder);
        }else {//修改订单
            //设置修改时间
            hotelOrder.setModifyDate(new Date());
            //修改修改人
            hotelOrder.setModifiedBy(user.getId());
            itripHotelOrderMapper.updateItripHotelOrder(hotelOrder);
            //根据订单编号删除订单联系人信息
            itripOrderLinkUserMapper.deleteItripOrderLinkUserByOrderId(hotelOrder.getId());
        }
        //3.添加订单联系人
        for (ItripUserLinkUser itripUserLinkUser : linkUser){
            //创建入住人对象
            ItripOrderLinkUser orderLinkUser = new ItripOrderLinkUser();
            BeanUtils.copyProperties(itripUserLinkUser,orderLinkUser);
            //设置入住人的编号
            orderLinkUser.setLinkUserId(itripUserLinkUser.getId());
            //设置订单编号
            orderLinkUser.setOrderId(hotelOrder.getId());
            orderLinkUser.setCreationDate(new Date());
            orderLinkUser.setCreatedBy(user.getId());
            itripOrderLinkUserMapper.insertItripOrderLinkUser(orderLinkUser);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("id",hotelOrder.getId());
        result.put("orderNo",hotelOrder.getOrderNo());
        System.out.println(result);
        return result;
    }

    @Override
    public ItripPersonalOrderRoomVO queryPersonalOrderRoomInfoByOrderId(Long id) throws Exception {
        ItripPersonalOrderRoomVO personalOrderRoomInfo = itripHotelOrderMapper.getPersonalOrderRoomInfoByOrderId(id);
        return personalOrderRoomInfo;
    }

    @Override
    public boolean getIsSupportOffLinePayByOrderId(Long id) throws Exception {
        Integer payType = itripHotelOrderMapper.getIsSupportOffLinePayByOrderId(id);
        if(payType==2||payType==3){
            return true;
        }
        return false;
    }

    @Override
    public boolean itriptxModifyItripHotelOrder(ItripModifyHotelOrderVO itripModifyHotelOrderVO, ItripUser itripUser) throws Exception {
        //修改订单的4个数据
        ItripHotelOrder hotelOrder =new ItripHotelOrder();
        hotelOrder.setId(itripModifyHotelOrderVO.getId());
        hotelOrder.setOrderStatus(Constants.ORDER_STATUS.PAY_SUCCESS);
        hotelOrder.setPayType(itripModifyHotelOrderVO.getPayType());
        hotelOrder.setModifyDate(new Date());
        hotelOrder.setModifiedBy(itripUser.getId());
        itripHotelOrderMapper.updateItripHotelOrder(hotelOrder);
        //2.修改三个字段
        ItripHotelOrder itripHotelOrder = this.getItripHotelOrderById(itripModifyHotelOrderVO.getId());
        Map<String,Object> params = new HashMap<>();
        params.put("roomId",itripHotelOrder.getRoomId());
        params.put("count",itripHotelOrder.getCount());
        params.put("modifyDate",new Date());
        params.put("modifiedBy",itripUser.getId());
        params.put("checkInDate",itripHotelOrder.getCheckInDate());
        params.put("checkOutDate",itripHotelOrder.getCheckOutDate());
        itripHotelTempStoreMapper.flushTempStore(params);
        return true;
    }

}
